package com.wfuhui.book.ui.book;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.wfuhui.book.MainActivity;
import com.wfuhui.book.R;
import com.wfuhui.book.model.Book;
import com.wfuhui.book.model.Evaluation;
import com.wfuhui.book.model.Member;
import com.wfuhui.book.ui.login.LoginActivity;
import com.wfuhui.book.ui.order.ConfirmActivity;
import com.wfuhui.book.util.Constant;
import com.wfuhui.book.util.GlideImageLoader;
import com.wfuhui.book.util.PreferencesService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 详情
 */
public class DetailActivity extends AppCompatActivity implements View.OnClickListener {

    private Book book = new Book();

    private TextView name, author, describe, num,price;

    private Button jieyue, addcart, readNow,buynow;

    private ImageView main;

    private ListView evaluationLv;

    private EvaluationAdapter evaluationAdapter = new EvaluationAdapter();

    private List<Evaluation> evaluationList = new ArrayList<>();

    private Integer total;

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        //返回按钮点击事件
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        price = findViewById(R.id.price);
        name = findViewById(R.id.name);
        author = findViewById(R.id.author);
        int id = getIntent().getIntExtra("id", 0);

        jieyue = findViewById(R.id.jieyue);
        addcart = findViewById(R.id.addcart);
        readNow = findViewById(R.id.readNow);
        buynow = findViewById(R.id.buynow);

        jieyue.setOnClickListener(this);
        addcart.setOnClickListener(this);
        readNow.setOnClickListener(this);
        buynow.setOnClickListener(this);

        main = findViewById(R.id.main);
        main.setOnClickListener(this);

        num = findViewById(R.id.num);

        describe = findViewById(R.id.describe);

        evaluationLv = findViewById(R.id.evaluation);
        evaluationLv.setAdapter(evaluationAdapter);
        this.getBook(id);
        this.getEvaluation(id);
        this.getcartNum();
    }

    /**
     * 评价
     */
    class EvaluationAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return evaluationList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View v = LayoutInflater.from(DetailActivity.this).inflate(R.layout.evaluation_item, null);
            final Evaluation evaluation = evaluationList.get(i);
            new GlideImageLoader().displayImage(DetailActivity.this, evaluation.getMember().getAvatarUrl(), (ImageView) v.findViewById(R.id.avatar));
            TextView nickname = v.findViewById(R.id.nickname);
            nickname.setText(evaluation.getMember().getNickname());
            TextView time = v.findViewById(R.id.time);
            time.setText(evaluation.getCreateTime());
            TextView content = v.findViewById(R.id.content);
            content.setText(evaluation.getContent());

            return v;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    new GlideImageLoader().displayImage(DetailActivity.this, book.getPicUrl(), (ImageView) findViewById(R.id.pic));
                    name.setText(book.getBookName());
                    author.setText(book.getAuthor());
                    describe.setText(book.getDescribe());
                    price.setText( price.getText()+ "："+ book.getPrice()+"");
                    break;
                case 3:
                    String info = msg.getData().getString("msg");
                    Toast.makeText(DetailActivity.this, info, Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    evaluationAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    /**
     * 查询图书
     *
     * @param id
     */
    private void getBook(int id) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/book/detail?id=" + id)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/book/detail", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/book/list", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if (code == 0) {
                        JSONObject bookJson = json.getJSONObject("book");
                        book.setId(bookJson.getInt("id"));
                        book.setBookName(bookJson.getString("bookName"));
                        book.setPicUrl(bookJson.getString("picUrl"));
                        book.setPrice(bookJson.getDouble("price"));
                        book.setAuthor(bookJson.getString("author"));
                        book.setDescribe(bookJson.getString("describe").length() > 50 ? bookJson.getString("describe").substring(0, 50) : bookJson.getString("describe"));
                        handler.sendEmptyMessage(1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void getcartNum() {
        PreferencesService preferencesService = new PreferencesService(this);
        String token = preferencesService.get("token");
        if (token == null || "".equals(token)) {
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/cart/total")
                .addHeader("token", token)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/cart/total", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/cart/total", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if (code == 0) {
                        total = json.getInt("total");
                        handler.sendEmptyMessage(2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 评价
     *
     * @param bookId
     */
    private void getEvaluation(Integer bookId) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/evaluation/list?bookId=" + bookId)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/evaluation/list", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/evaluation/list", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if (code == 0) {
                        JSONArray evaluationArr = json.getJSONArray("evaluations");
                        for (int i = 0; i < evaluationArr.length(); i++) {
                            JSONObject evaluationJson = evaluationArr.getJSONObject(i);
                            Evaluation evaluation = new Evaluation();
                            evaluation.setId(evaluationJson.getInt("id"));
                            evaluation.setContent(evaluationJson.getString("content"));
                            evaluation.setCreateTime(evaluationJson.getString("createTime"));
                            JSONObject memberObj = evaluationJson.getJSONObject("member");
                            Member member = new Member();
                            member.setAvatarUrl(memberObj.getString("avatarUrl"));
                            member.setNickname(memberObj.getString("nickname"));
                            evaluation.setMember(member);
                            evaluationList.add(evaluation);
                        }
                        handler.sendEmptyMessage(5);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        PreferencesService preferencesService = new PreferencesService(this);
        String token = preferencesService.get("token");
        Intent intent = null;
        switch (v.getId()) {
            case R.id.jieyue:
                if (token == null || "".equals(token)) {
                    intent = new Intent(DetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                jieyue();
                break;
            case R.id.buynow:

                if (token == null || "".equals(token)) {
                    intent =  new Intent(DetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }


                intent = new Intent(DetailActivity.this, ConfirmActivity.class);
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("bookId", book.getId());
                    jsonObject.put("bookName", book.getBookName());
                    jsonObject.put("author", book.getAuthor());
                    jsonObject.put("picUrl", book.getPicUrl());
                    jsonObject.put("price", book.getPrice());
                    jsonObject.put("num", 1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONArray jsonArray = new JSONArray();
                jsonArray.put(jsonObject);
                intent.putExtra("payBook", jsonArray.toString());
                startActivity(intent);

                break;
            case R.id.main:
                intent = new Intent(DetailActivity.this, MainActivity.class);
                startActivity(intent);
                break;

            case R.id.addcart:
                if (token == null || "".equals(token)) {
                    intent = new Intent(DetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                addCart();
                break;
            case R.id.readNow:
                Intent bookRead = new Intent(DetailActivity.this, BookReadActivity.class);
                JSONObject bookObj = new JSONObject();
                try {
                    bookObj.put("bookId", book.getId());
                    bookObj.put("bookName", book.getBookName());
                    bookObj.put("describe", book.getDescribe());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                bookRead.putExtra("readBook", bookObj.toString());
                startActivity(bookRead);
                break;
        }
    }

    /**
     * 添加书架
     */
    private void addCart() {
        OkHttpClient client = new OkHttpClient();

        JSONObject json = new JSONObject();
        try {
            json.put("bookId", book.getId());
            json.put("bookName", book.getBookName());
            json.put("picUrl", book.getPicUrl());
            json.put("author", book.getAuthor());
            json.put("price", book.getPrice());
            json.put("num", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = FormBody.create(json.toString(), MediaType.parse("application/json; charset=utf-8"));

        PreferencesService preferencesService = new PreferencesService(this);
        String token = preferencesService.get("token");
        if (token == null || "".equals(token)) {
            return;
        }

        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/cart/save")
                .addHeader("token", token)
                .post(requestBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/cart/save", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/cart/save", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if (code == 0) {
                        Message msg = new Message();
                        msg.what = 3;
                        Bundle bundle = new Bundle();
                        bundle.putString("msg", "添加成功");
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    /**
     * 借阅
     */
    private void jieyue() {
        OkHttpClient client = new OkHttpClient();

        JSONObject json = new JSONObject();
        try {
            Log.d("TAG", "jieyue: "+ book.getId());
            json.put("bookid", book.getId());
            json.put("bookname", book.getBookName());
            json.put("bookimage", book.getPicUrl());
            json.put("bookauthor", book.getAuthor());
            json.put("bookprice", book.getPrice());
            json.put("num", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = FormBody.create(json.toString(), MediaType.parse("application/json; charset=utf-8"));

        PreferencesService preferencesService = new PreferencesService(this);
        String token = preferencesService.get("token");
        if (token == null || "".equals(token)) {
            return;
        }

        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/jieyue/save")
                .addHeader("token", token)
                .post(requestBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/jieyue/save", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/jieyue/save", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if (code == 0) {
                        Message msg = new Message();
                        msg.what = 3;
                        Bundle bundle = new Bundle();
                        bundle.putString("msg", "借阅成功！");
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                    }
                    else  {
                        Message msg = new Message();
                        msg.what = 3;
                        Bundle bundle = new Bundle();
                        bundle.putString("msg","错误！"+ json.getString("msg"));
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
